<template>
  <div class="home"
       :class="{'isSetting': themeConfig.isSetting, 'loading': initLoading}">
    <img class="seat_img"
         src="./../assets/images/setting/theme1.jpg"
         alt="">
    <setting :class="{'active': themeConfig.isSetting}"></setting>
    <tips ref="tips"
          @sureHandle="tipsSureHandle"></tips>
    <Organ ref="listSelect"
           :isShowAccountList="isShowAccountList"
           @listenTreeId="listenTreeId"></Organ>
    <div class="home-content">
      <meteor :backgroundTheme="themeConfig.backgroundTheme"></meteor>
      <div class="main-content">
        <header-vue :companyName="companyName"
                    :userId="userId"></header-vue>
        <keep-alive>
          <router-view class="router-view"
                       :pageConfig="pageConfig"
                       ref="routerView"></router-view>
        </keep-alive>
      </div>
    </div>
  </div>
</template>

<script>
import Meteor from './page/Meteor.vue'
import Setting from './page/Setting.vue'
import HeaderVue from './components/HeaderVue.vue'
import Tips from './components/Tips.vue'
import Organ from './components/Organ.vue'
import { calculationModuleSeat, moduleToModuleList, showSelectModule } from '@/utils/modulePosition'
export default {
  name: 'home',
  components: {
    Meteor,
    Setting,
    HeaderVue,
    Tips,
    Organ
  },
  data () {
    return {
      organId: '',
      pageConfig: false, // 是否已经获取模块配置
      companyName: '',
      oldCompanyName: '',
      isShowAccountList: false, // 是否打开组织机构
      userId: '',
      initLoading: true // 初始化加载
    }
  },
  computed: {
    themeConfig () {
      return this.$store.state.themeConfig
    },
    moduleList () {
      return this.$store.state.moduleList
    },
    isIndex () {
      return this.$store.state.isIndex
    }
  },
  methods: {
    // 提示语确定处理函数，有修改标题，和请求修改标题失败的情况，还有普通请求失败
    // showTips的时候传进去的时候，定义了1为编辑标题, 2为修改标题失败
    // data为{type: '', message: ''}
    tipsSureHandle (data) {
      if (data.type === 1) {
        // 请求编辑标题
        this.saveCompanyName(data.message)
      } else if (data.type === 2) {
        // 重新保存
        this.editCompanyName()
      } else {
        if (this.organId) {
          this.listenTreeId(this.organId, this.organModel)
        } else {
          // 重新加载组织树
          this.$refs.listSelect.loadOrganTree()
        }
      }
    },
    // 显示提示弹窗
    showTips (showMessage) {
      this.$refs.tips.showTips(showMessage)
    },
    // 打开组织机构
    showAccountList () {
      this.isShowAccountList = true
      this.$refs.listSelect.selectOrgan(this.organId, this.organModel)
    },
    // 隐藏组织机构
    closeAccount () {
      this.isShowAccountList = false
    },
    // 打开修改公司名字的界面
    editCompanyName () {
      this.showTips({ isEdit: true, showMessage: this.companyName, showType: 1 })
    },
    // 编辑标题
    saveCompanyName (companyName) {
      this.commonApi.saveOrganAlisaName({ organId: this.organId, alisaName: companyName }).then((res) => {
        if (res.data.code === '0') {
          this.companyName = companyName
          this.oldCompanyName = companyName
        } else {
          this.companyName = this.oldCompanyName
          this.showTips({ showMessage: '保存失败，请稍后重试', showType: 2 })
        }
      }, (res) => {
        this.companyName = this.oldCompanyName
        this.showTips({ showMessage: '保存失败，请稍后重试', showType: 2 })
      })
    },
    // 获取公司显示的名字
    getCompanyName () {
      this.commonApi.getOrganAlisaName({ organId: this.organId }).then((res) => {
        if (res.data.code === '0') {
          this.companyName = res.data.data
          this.oldCompanyName = res.data.data
        } else {
        }
      }, (res) => {
      })
    },
    // 获取用户账号下有哪些模块
    getModuleList () {
      this.commonApi.getModuleList().then(res => {
        if (res.data.code === '0') {
          let moduleList = showSelectModule({ moduleList: this.moduleList, data: res.data.data })
          this.$store.commit('CHANGEMODULELIST', moduleList)
        } else {
          this.showTips('请求失败，点击确认继续刷新')
        }
      }, res => {
        this.showTips('请求失败，点击确认继续刷新')
      })
    },
    // 获取页面配置
    getPageConfig (params = {}) {
      return new Promise((resolve) => {
        let apiName = 'getPageConfig'
        if (JSON.stringify(params) !== '{}') {
          apiName = 'getPageCfgInfoByUserId'
        }
        this.commonApi[apiName](params).then(res => {
          console.log('getPageConfig res =========> ', res)
          if (res.data.code === '0') {
            let data = res.data.data
            if (process.env.NODE_ENV === 'development') {
            }
            let backgroundTheme = data.layoutId ? parseInt(data.layoutId - 1) : 0
            let moduleTheme = data.frameId === '1' ? 'flat' : 'default'
            let echartsTheme = data.widgetId === '1' ? 'flat' : 'default'
            this.$store.commit('CHANGETHEMECONFIG', {
              type: 'all',
              newData: {
                isSetting: false,
                backgroundTheme: backgroundTheme,
                moduleTheme: moduleTheme,
                echartsTheme: echartsTheme
              }
            })
            let moduleMessage = calculationModuleSeat(data.modules)
            let moduleList = moduleToModuleList({ module: moduleMessage.module, moduleId: moduleMessage.moduleId, moduleObj: moduleMessage.moduleObj, moduleList: this.moduleList })
            this.$store.commit('CHANGEMODULELIST', moduleList)
            this.$nextTick(function () {
              this.pageConfig = true
              resolve()
            })
          } else {
            this.showTips('请求失败，点击确认继续刷新')
          }
        }, res => {
          this.showTips('请求失败，点击确认继续刷新')
        })
      })
    },
    // 请求接口后返回organId
    listenTreeId (id, model, type) {
      if (type === 'abnormal') {
        this.abnormal = true
        return false
      } else {
        if (process.env.NODE_ENV === 'development') {
          // id = 1300
        }
        this.organId = id
        this.organModel = model
        this.companyName = model.name
        this.oldCompanyName = model.name
        this.$store.commit('CHANGEORGAN', { organId: id, organModel: model })
        // 关闭加载动画
        this.abnormal = false
        // document.getElementById('loading').classList.add('loaded-api')
        this.isCount = true
      }
      // 隐藏组织机构
      this.isShowAccountList = false
      // 获取公司别名
      this.getCompanyName()
    },
    // 二级页面请求数据
    secondPageGetData () {
      this.$refs.routerView.getData()
    },
    // 演示7秒显示页面
    loaded () {
      // setTimeout(() => {
      this.initLoading = false
      document.getElementById('loading').style.display = 'none'
      // }, 6400)
    },
    // 自适应
    resizeChart () {
      this.$refs.routerView.resizeChart()
    },
    // 前端写死模块配置
    pageConfigNotApi (callback) {
      let data = {
        layoutId: 0,
        frameId: '0',
        widgetId: '0'
      }
      if (process.env.NODE_ENV === 'development') {
        data.modules = [
          // {
          //   'id': '47',
          //   'code': 'MBDCQK',
          //   'name': '目标达成概况',
          //   'pointX': '2',
          //   'pointY': '0',
          //   'numsX': '2',
          //   'numsY': '2',
          //   'seat': '[]'
          // },
          // {
          //   'id': '48',
          //   'code': 'ZJSRQS',
          //   'name': '租金收入趋势',
          //   'pointX': '0',
          //   'pointY': '0',
          //   'numsX': '2',
          //   'numsY': '2',
          //   'seat': '[]'
          // },
          // {
          //   'id': '49',
          //   'code': 'BNZLQS',
          //   'name': '本年租赁趋势',
          //   'pointX': '0',
          //   'pointY': '1',
          //   'numsX': '2',
          //   'numsY': '2',
          //   'seat': '[]'
          // },
          // {
          //   'id': '52',
          //   'code': 'BNQYBH',
          //   'name': '本年签约变化',
          //   'pointX': '2',
          //   'pointY': '1',
          //   'numsX': '2',
          //   'numsY': '2',
          //   'seat': '[]'
          // }
          {
            'id': '46',
            'code': 'LeasingResources',
            'name': '资源租赁情况',
            'pointX': '0',
            'pointY': '0',
            'numsX': '2',
            'numsY': '4',
            'seat': '[]'
          },
          {
            'id': '50',
            'code': 'GoalsAchieved',
            'name': '管理主体目标达成',
            'pointX': '2',
            'pointY': '0',
            'numsX': '4',
            'numsY': '4',
            'seat': '[]'
          },
          {
            'id': '51',
            'code': 'VacancyInTheYear',
            'name': '本年空置情况',
            'pointX': '0',
            'pointY': '1',
            'numsX': '2',
            'numsY': '4',
            'seat': '[]'
          }
        ]
      }
      let backgroundTheme = data.layoutId ? parseInt(data.layoutId - 1) : 0
      let moduleTheme = data.frameId === '1' ? 'flat' : 'default'
      let echartsTheme = data.widgetId === '1' ? 'flat' : 'default'
      this.$store.commit('CHANGETHEMECONFIG', {
        type: 'all',
        newData: {
          isSetting: false,
          backgroundTheme: backgroundTheme,
          moduleTheme: moduleTheme,
          echartsTheme: echartsTheme
        }
      })
      let moduleMessage = calculationModuleSeat(data.modules)
      let moduleList = moduleToModuleList({ module: moduleMessage.module, moduleId: moduleMessage.moduleId, moduleObj: moduleMessage.moduleObj, moduleList: this.moduleList })
      this.$store.commit('CHANGEMODULELIST', moduleList)
      this.$nextTick(function () {
        this.pageConfig = true
        callback()
      })
    }
  },
  mounted () {
    this.initLoading = true
    document.getElementById('loading').classList.add('loaded-api')
    let urlParams = window.location.href.indexOf('?') > -1 ? window.location.href.split('?')[1] : []
    let paramsArr = urlParams.length > 0 ? urlParams.split('&') : []
    let user = {}
    let message = []
    let pageConfig = {}
    paramsArr.forEach((item) => {
      message = item.split('=')
      user[message[0]] = message[1]
    })
    // 跳过接口出错的时候，显示页面, environmental = false的时候，正常流程
    if (process.env.NODE_ENV === 'development') {
      let environmental = true
      if (environmental) {
        this.pageConfigNotApi(this.loaded)
        return false
      }
    }
    // 获取页面配置
    if (user.userId) {
      this.userId = user.userId
      pageConfig = {
        organId: user.organId,
        userId: user.userId
      }
      this.getPageConfig(pageConfig).then(res => {
        this.loaded()
        this.organId = user.organId
        this.$store.commit('CHANGEORGAN', { organId: user.organId, organModel: {} })
        this.getCompanyName()
      }, res => {
        this.loaded()
      })
    } else {
      if (process.env.NODE_ENV === 'development') {
        let loginMessage = {
          username: 13538143596,
          password: 'bbbb2222'
          // username: 18818596803,
          // password: 222222
          // username: 'SG170001',
          // password: 'abc123'
        }
        this.commonApi.login(loginMessage).then(res => {
          this.getModuleList()
          this.getPageConfig(pageConfig).then(res => {
            this.loaded()
            this.$refs.listSelect.loadOrganTree()
          }, res => {
            this.loaded()
          })
        })
      } else {
        this.getModuleList()
        this.getPageConfig(pageConfig).then(res => {
          this.loaded()
          this.$refs.listSelect.loadOrganTree()
        }, res => {
          this.loaded()
        })
      }
    }
  },
  watch: {
    isIndex (val) {
      if (!val) {
        this.secondPageGetData()
      }
    }
  }
}
</script>

<style lang="scss">
body {
  font-size: 12px;
}
.home {
  position: relative;
  overflow: hidden;
  min-width: 1580px;
  background: #161c24;
  &.loading {
    opacity: 0;
    height: 0;
  }
  &.isSetting {
    .home-content {
      transform: translate3d(0, 100%, 0);
      transition: transform 0.5s;
    }
  }
  .home-content {
    width: 100%;
    height: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: 100;
    overflow: hidden;
    transform: translate3d(0, 0, 0);
    transition: transform 0.5s;
    .main-content {
      width: 100%;
      height: 100%;
      position: absolute;
      bottom: 0;
      left: 0;
      z-index: 100;
      .header {
        width: 100%;
        position: relative;
        z-index: 100;
      }
    }
  }
  .seat_img {
    width: 100%;
    display: block;
    opacity: 0;
  }
}
</style>
